//
//  HomeViewController.m
//  JiuLe
//
//  Created by 黄鑫 on 16/8/23.
//  Copyright © 2016年 Fine. All rights reserved.
//

#import "HomeViewController.h"
#import "HomeCollectionViewCell.h"
#import "HomeHeadCollectionReusableView.h"
#import "HomeFooterCollectionReusableView.h"
#import "JLServiceWebViewController.h"
#import "MessageViewController.h"
#import "Common.h"
#import "Costants.h"
#import "PersonalViewController.h"
#import "HealthViewController.h"
#import "HealthReportViewController.h"
#import "ChallengeYourselfViewController.h"
#import "LoginViewController.h"
#import "MallViewController.h"
#import "ArticleViewController.h"
#import "RankingViewController.h"
#import "CheckView.h"
#import "MyGradesViewController.h"
#import "ActivityViewController.h"
#import "EquipmentViewController.h"
#import "HousekeeperViewController.h"
#import "UserHelpViewController.h"
#import "DoctorPulseViewController.h"
#import "AppDelegate.h"

@interface HomeViewController ()<CheckViewDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *mainCollectionView;
@property (strong, nonatomic) HomeHeadCollectionReusableView *mainCollectHeaderView;
@property (strong, nonatomic) HomeFooterCollectionReusableView *mainCollectFooterView;
@property (strong, nonatomic) NSMutableArray *arrImageName;//collect数据源
@property (strong, nonatomic) NSMutableArray *arrTitle;//标签名
@property (assign, nonatomic) NSInteger headerViewHieght;
@property (strong, nonatomic) UIAlertView *alertView;
@property (strong, nonatomic) NSDictionary *dicResult;
@property (strong, nonatomic) NSDictionary *activity;
@property (strong, nonatomic) NSDictionary *tianshi;
@property (strong, nonatomic) CheckView *checkView;

@end

@implementation HomeViewController

static NSString *const collIdentifier = @"HomeCollectionViewCell";
static NSString *const headerId = @"headerId";
static NSString *const footerId = @"footerId";

- (void)viewDidLoad {
    [super viewDidLoad];
    [self showNavBarWithRightImage:[UIImage imageNamed:@"icon_user"] LeftBtnImage:[UIImage imageNamed:@"icon_checkin"] andRightBtnAction:@selector(myAction) andLeftBtnAction:@selector(checkin) andRightBadge:0 andLeftBage:0 title:@"久乐健康" barColor:nil];
    _mainCollectionView.backgroundColor = RGB(194, 194, 194);
    [_mainCollectionView registerNib:[UINib nibWithNibName:@"HomeCollectionViewCell" bundle:nil]  forCellWithReuseIdentifier:collIdentifier];
    [_mainCollectionView registerNib:[UINib nibWithNibName:@"HomeHeadCollectionReusableView" bundle:nil]  forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerId];
    [_mainCollectionView registerNib:[UINib nibWithNibName:@"HomeFooterCollectionReusableView" bundle:nil]  forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footerId];
    //注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tongzhi) name:@"TUISONGTONGZHI" object:nil];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    [self requestNotice];
    [self.navigationController setToolbarHidden:YES animated:YES];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
     AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    if (appDelegate.receivedNotification) {
        appDelegate.receivedNotification = NO;
        [self housekeeper];
    }
}

- (void)tongzhi{
    [self housekeeper];
}

#pragma mark - 数据请求
- (void)getCheckInfo{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:[[NSUserDefaults standardUserDefaults] objectForKey:UserDataID] forKey:@"user_id"];
    [[BaseDataRequest alloc] getCheckInfo:dict withBlock:^(id responseObject, NSString *status, NSError *error) {
        [_checkView requestEnd];
        if ([status isEqualToString:@"0"]) {
            _dicResult = [responseObject objectForKey:@"result"];
            [_checkView initData:_dicResult];
        }else{
            if (error != nil) {
                TIPSFORVIEW(@"请检测网络设置");
            }else{
                TIPSFORVIEW(@"获取签到信息失败");
            }
        }
    }];
}

- (void)setActivityInfo{
    if (![[_activity objectForKey:@"isread"] isEqualToString:@"yes"]){
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:[[NSUserDefaults standardUserDefaults] objectForKey:UserDataID] forKey:@"user_id"];
        NSString *type = [NSString stringWithFormat:@"%d",[[_activity objectForKey:@"type"] intValue]];
        [dict setObject:[_activity objectForKey:@"id"] forKey:@"id"];
        [dict setObject:type forKey:@"type" ];
        [[BaseDataRequest alloc] setActivityInfo:dict withBlock:^(id responseObject, NSString *status, NSError *error) {
        }];
    }
}

- (void)setTianshiInfo{
    if (![[_tianshi objectForKey:@"isread"] isEqualToString:@"yes"]){
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:[[NSUserDefaults standardUserDefaults] objectForKey:UserDataID] forKey:@"user_id"];
        NSString *type = [NSString stringWithFormat:@"%d",[[_tianshi objectForKey:@"type"] intValue]];
        [dict setObject:[_tianshi objectForKey:@"id"] forKey:@"id"];
        [dict setObject:type forKey:@"type" ];
        [[BaseDataRequest alloc] setActivityInfo:dict withBlock:^(id responseObject, NSString *status, NSError *error) {
        }];
    }
}

- (void)requestCheck{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:[[NSUserDefaults standardUserDefaults] objectForKey:UserDataID] forKey:@"user_id"];
    [[BaseDataRequest alloc] requestCheck:dict withBlock:^(id responseObject, NSString *status, NSError *error) {
        if ([status isEqualToString:@"0"]) {
            TIPSFORVIEW(@"签到成功");
            [_checkView removeFromSuperview];
        }else{
            if (error != nil) {
                TIPSFORVIEW(@"请检测网络设置");
            }else{
                TIPSFORVIEW(@"签到失败");
            }
            
        }
    }];
}

- (void)requestNotice{
    if([[[NSUserDefaults standardUserDefaults] objectForKey:UserDataID] isEqualToString:@""])
        return;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:[[NSUserDefaults standardUserDefaults] objectForKey:UserDataID] forKey:@"user_id"];
    [[BaseDataRequest alloc] requestNotice:dict withBlock:^(id responseObject, NSString *status, NSError *error) {
        if ([status isEqualToString:@"0"]) {
            NSDictionary *result = [responseObject objectForKey:@"result"];
            _activity = [result objectForKey:@"activity"];
            _tianshi = [result objectForKey:@"tianshi"];
            if ([[_activity objectForKey:@"isread"] isEqualToString:@"yes"]) {
                _mainCollectHeaderView.imageActivity.hidden = YES;
            }else{
                _mainCollectHeaderView.imageActivity.hidden = NO;
            }
            if ([[_tianshi objectForKey:@"isread"] isEqualToString:@"yes"]) {
                _mainCollectHeaderView.imageAngel.hidden = YES;
            }else{
                _mainCollectHeaderView.imageAngel.hidden = NO;
            }
        }else{
        }
    }];
}

#pragma mark ---- UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.arrTitle.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    HomeCollectionViewCell *cell = (HomeCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:collIdentifier forIndexPath:indexPath];
    if (indexPath.row > 6) {
        cell.labelName.hidden = YES;
        cell.imageName.hidden = YES;
    }else{
        cell.labelName.hidden = NO;
        cell.imageName.hidden = NO;
        cell.imageName.image = [UIImage imageNamed:self.arrImageName[indexPath.row]];
        cell.labelName.text = self.arrTitle[indexPath.row];
    }
    return cell;
}

// 和UITableView类似，UICollectionView也可设置段头段尾
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if([kind isEqualToString:UICollectionElementKindSectionHeader]){
        _mainCollectHeaderView = [_mainCollectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headerId forIndexPath:indexPath];
        if(_mainCollectHeaderView == nil){
            _mainCollectHeaderView = [[HomeHeadCollectionReusableView alloc] init];
        }
        _mainCollectHeaderView.backgroundColor = RGB(75, 162, 200);
        _mainCollectHeaderView.imageAngel.hidden = YES;
        _mainCollectHeaderView.imageConnect.hidden = YES;
        _mainCollectHeaderView.imageActivity.hidden = YES;
        _mainCollectHeaderView.labelRanking.hidden = YES;
        [_mainCollectHeaderView.btnRanking addTarget:self action:@selector(ranking) forControlEvents:UIControlEventTouchUpInside];
        [_mainCollectHeaderView.btnActivity addTarget:self action:@selector(toActivity) forControlEvents:UIControlEventTouchUpInside];
        [_mainCollectHeaderView.btnConnect addTarget:self action:@selector(connectBEL) forControlEvents:UIControlEventTouchUpInside];
        [_mainCollectHeaderView.btnAngel addTarget:self action:@selector(housekeeper) forControlEvents:UIControlEventTouchUpInside];
        return _mainCollectHeaderView;
    }else if([kind isEqualToString:UICollectionElementKindSectionFooter]){
        _mainCollectFooterView = [_mainCollectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:footerId forIndexPath:indexPath];
        if(_mainCollectFooterView == nil){
            _mainCollectFooterView = [[HomeFooterCollectionReusableView alloc] init];
        }
        [_mainCollectFooterView.btnResetvation addTarget:self action:@selector(toGoodMedicalNetwork) forControlEvents:UIControlEventTouchUpInside];
        [_mainCollectFooterView.btnPulse addTarget:self action:@selector(toDoctorPulse) forControlEvents:UIControlEventTouchUpInside];
        return _mainCollectFooterView;
    }
    return nil;
}

#pragma mark ---- UICollectionViewDelegateFlowLayout
//item宽高
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
        return (CGSize){floorf(KScreenWidth/3),floorf(KScreenWidth/3)};
}

//四周边间距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    if (KScreenWidth == 320) {
        return UIEdgeInsetsMake(0,0.5, 0,0.5);
    }else{
        return UIEdgeInsetsMake(0,-1, 0,0);
    }
}

//行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    if (KScreenWidth == 320) {
        return 0.5f;
    }else{
        return 0.5f;
    }
}

//列间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
       // return 0.0f;
    return .0f;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return (CGSize){KScreenWidth,self.headerViewHieght};
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    if (KScreenWidth == 320) {
        return (CGSize){KScreenWidth,56};
    }else{
        return (CGSize){KScreenWidth,60};
    }
}

#pragma mark ---- UICollectionViewDelegate
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

-(void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath{
    HomeCollectionViewCell *cell = (HomeCollectionViewCell *)[_mainCollectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor groupTableViewBackgroundColor];
}

- (void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath{
    HomeCollectionViewCell *cell = (HomeCollectionViewCell *)[_mainCollectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
}

// 选中某item
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSString *strTitle = self.arrTitle[indexPath.row];
    if ([strTitle isEqualToString:@"健康数据"]) {
        if (![self logInspection]) {
            return;
        }
        HealthViewController *health = [[UIStoryboard storyboardWithName:@"HealthViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"HealthViewController"];
        [self.navigationController pushViewController:health animated:YES];
    }else if ([strTitle isEqualToString:@"健康报告"]) {
        if (![self logInspection]) {
            return;
        }
        HealthReportViewController *healthReport = [[UIStoryboard storyboardWithName:@"HealthReportViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"HealthReportViewController"];
        [self.navigationController pushViewController:healthReport animated:YES];
    }else if ([strTitle isEqualToString:@"商城"]) {
        
       
        MallViewController *mall = [[UIStoryboard storyboardWithName:@"MallViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"MallViewController"];
        NSString *str = [[NSUserDefaults standardUserDefaults] objectForKey:UserDataID];
        if ([str isEqualToString:@""] || str == nil || str == NULL) {
            mall.youke = YES;
        }
        [self.navigationController pushViewController:mall animated:YES];
    }else if ([strTitle isEqualToString:@"健康预警"]) {
        if (![self logInspection]) {
            return;
        }
        MessageViewController *message = getStoryOfControllerInstance(@"MessageViewController");
        [self.navigationController pushViewController:message animated:YES];
    }else if ([strTitle isEqualToString:@"自我挑战"]) {
        UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"提示" message:@"蓝牙功能尚在开发中，敬请期待" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
        alertV.tag =1;
        [alertV show];
        /*
        ChallengeYourselfViewController *challengeYourself = [[UIStoryboard storyboardWithName:@"ChallengeYourselfViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"ChallengeYourselfViewController"];
        [self.navigationController pushViewController:challengeYourself animated:YES];*/
    }else if ([strTitle isEqualToString:@"用户帮助"]) {
        
        UserHelpViewController *user = [[UserHelpViewController alloc]init];
        [self.navigationController pushViewController:user animated:YES];
        
    }else if ([strTitle isEqualToString:@"文章订阅"]) {
        ArticleViewController *ArticleVC = [[UIStoryboard storyboardWithName:@"ArticleViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"ArticleViewController"];
        [self.navigationController pushViewController:ArticleVC animated:YES];
    }else if ([strTitle isEqualToString:@""]) {
        
    }else if ([strTitle isEqualToString:@"第九个itme"]){
        
        
    }
    HomeCollectionViewCell *cell = (HomeCollectionViewCell *)[_mainCollectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [UIView animateWithDuration:0.3 animations:^{
        cell.backgroundColor = [UIColor whiteColor];
    } completion:^(BOOL finished) {
        
    }];
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
    HomeCollectionViewCell *cell = (HomeCollectionViewCell *)[_mainCollectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
}

#pragma mark - UIAlertViewDelehgate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(alertView.tag == 1)
        return;
    if (buttonIndex == 1) {
        LoginViewController *login = getStoryOfControllerInstance(@"LoginViewController");
        BaseNavController *baseNav = [[BaseNavController alloc] initWithRootViewController:login];
        [UIApplication sharedApplication].delegate.window.rootViewController = baseNav;
    }
}

#pragma mark - CheckViewDelegate
- (void)helpAction{
    if (![self logInspection]) {
        return;
    }
    if (_checkView.show == YES){
        _checkView.show = NO;
        [_checkView removeFromSuperview];
    }
    MyGradesViewController *grades = [[MyGradesViewController alloc]init];
    [self.navigationController pushViewController:grades animated:YES];
}

- (void)checkAction{
    [self requestCheck];
}

- (void)remonvView:(UIView *)view with:(NSString *)title{
    [view removeFromSuperview];
    if (![title isEqualToString:@""]) {
        TIPSFORVIEW(title);
    }
}

#pragma mark - set/get
- (NSInteger)headerViewHieght{
    if (KScreenWidth == 320) {
        return 130.0f;
    }else if(KScreenWidth == 375){
        return 168.0f;
    }else{
        return 200.0f;
    }
}

- (NSMutableArray *)arrTitle{
    if (_arrTitle == nil) {
        _arrTitle = [NSMutableArray arrayWithObjects:@"健康数据",@"健康报告",@"健康预警",@"商城",@"自我挑战",@"用户帮助",@"文章订阅",@"",@"第九个itme", nil];
    }
    return _arrTitle;
}

- (NSMutableArray *)arrImageName{
    if (_arrImageName == nil) {
        _arrImageName = [[NSMutableArray alloc]initWithObjects:@"icon_healthdata.png",@"icon_healthreport",@"icon_sos",@"icon_shoppingbag",@"icon_challenge",@"icon_userhelp",@"icon_news", nil];
    }
    return _arrImageName;
}

#pragma mark set/get
- (UIAlertView *)alertView{
    if (_alertView == nil) {
        _alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您尚未登录，是否立即登录" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
        _alertView.delegate = self;
    }
    return _alertView;
}

#pragma mark - 私有方法
- (void)ranking{
    if (![self logInspection]) {
        return;
    }
    RankingViewController *ranking = [[UIStoryboard storyboardWithName:@"RankingViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"RankingViewController"];
    [self.navigationController pushViewController:ranking animated:YES];
}

- (void)toActivity{
    if (![self logInspection] ) {
        return;
    }else if (_mainCollectHeaderView.imageActivity.hidden != YES){
        [self setActivityInfo];
    }
    ActivityViewController *activity = [[UIStoryboard storyboardWithName:@"ActivityViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"ActivityViewController"];
    [self.navigationController pushViewController:activity animated:YES];
}

- (void)connectBEL{
    UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"提示" message:@"蓝牙功能尚在开发中，敬请期待" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    alertV.tag =1;
    [alertV show];
    return;
    /*EquipmentViewController *activity = [[UIStoryboard storyboardWithName:@"EquipmentViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"EquipmentViewController"];
    [self.navigationController pushViewController:activity animated:YES];*/
}

- (void)housekeeper{
    if (![self logInspection]) {
        return;
    }else if(_mainCollectHeaderView.imageAngel.hidden != YES){
        [self setTianshiInfo];
    }
    HousekeeperViewController *housekeeper = [[UIStoryboard storyboardWithName:@"HousekeeperViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"HousekeeperViewController"];
    [self.navigationController pushViewController:housekeeper animated:YES];
}

- (void)myAction{
    if (_checkView.show == YES){
        _checkView.show = NO;
        [_checkView removeFromSuperview];
    }
    PersonalViewController *personal = [[UIStoryboard storyboardWithName:@"PersonalViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"PersonalViewController"];
    [self.navigationController pushViewController:personal animated:YES];
}

- (void)checkin{
    if (![self logInspection]) {
        return;
    }
    if (_checkView == nil) {
        _checkView =  [[[NSBundle mainBundle] loadNibNamed:@"CheckView" owner:nil options:nil] firstObject];
        _checkView.delegate = self;
    }
    if (_checkView.show == NO) {
        [self.view addSubview:_checkView];
        [_checkView requestData];
        [self getCheckInfo];
    }else{
        _checkView.show = NO;
        [_checkView removeFromSuperview];
    }
}

- (void)toGoodMedicalNetwork{
    JLServiceWebViewController *serviceWeb = [[JLServiceWebViewController alloc] initWithNibName:@"JLServiceWebViewController" bundle:nil];
    [self.navigationController pushViewController:serviceWeb animated:YES];
}

- (void)toDoctorPulse{
    DoctorPulseViewController *doctor= [[DoctorPulseViewController alloc] init];
    [self.navigationController pushViewController:doctor animated:YES];
}

- (BOOL)logInspection{
    NSString *str = [[NSUserDefaults standardUserDefaults] objectForKey:UserDataID];
    if ([str isEqualToString:@""] || str == nil || str == NULL) {
        [self.alertView show];
        return NO;
    }else{
        return YES;
    }
}

- (void)dealloc{
    //[[NSNotificationCenter defaultCenter] removeObserver:self name:@"tongzhi" object:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
